import {createStore} from 'vuex'
import {genRoutes} from '@/utils/router'
import router, {constantRoutes} from "@/router";

const isDev = process.env.NODE_ENV === 'development'
const store = createStore({
    state() {
        return {
            collapsed: false,
            tabsViewList: [],
            routes: [],
            menuList: [],
            permiss: null,
        }
    },
    getters: {
        getCollapsed: (state) => state.collapsed,
        getTabsView: (state) => state.tabsViewList,
        getRoutes: (state) => state.routes,
        getPermiss: (state) => state.permiss,
    },
    mutations: {
        TOGGLE_COLLAPSED: (state, payload) => {
            state.collapsed = payload
        },
        REMOVE_TABS: (state, payload) => {
            if (payload.length !== 0) {
                state.tabsViewList = state.tabsViewList.filter(item => payload.indexOf(item.path) === -1)
            } else {
                state.tabsViewList = []
            }
        },
        ADD_TABS: (state, payload) => {
            if (payload.path !== '/login') {
                state.tabsViewList.push(Object.assign({}, payload))
            }
        },
        /**
         * map存储菜单权限
         */
        SET_PAGE_PERMISSION: (state, payload) => {
            const permissMap = new Map()
            payload.forEach(item => {
                if (item.children && item.children.length && item.children[0].type === 2) {
                    permissMap.set(item.webUrl, item.children)
                }
            })
            state.permiss = permissMap
        },
        SET_ROUTES: (state, payload) => {
            state.routes = payload
        },
        CLEAR_CACHE: (state) => {
            state.routes.forEach(item => {
                if (item.name) {
                    router.removeRoute(item.name)
                }
            })
            Object.assign(state, {
                tabsViewList: [],
                routes: [],
                menuList: [],
                permiss: null
            })
        }
    },
    actions: {
        changeLoading({commit}, payload) {
            commit('CHANGE_LOADING', payload)
        },
        remove_Tabs({commit}, payload) {
            commit('REMOVE_TABS', payload)
        },
        add_Tabs({commit}, payload) {
            commit('ADD_TABS', payload)
        },
        convertRoutes({commit}, payload) {
            /**
             * permission  按钮权限
             * route 路由
             */
            const {permission, route} = genRoutes(payload)
            // 动态添加路由
            route.forEach(item => {
                router.addRoute(item)
            })
            commit('SET_PAGE_PERMISSION', permission)
            commit('SET_ROUTES', route)
        },
    }
})

export default store
